<template>
  <h1>增删改查系统</h1><br>
  <h3>删除&查询</h3>
  <li v-for="item in people">
    <label for={{item.id}}>姓名:{{ item.name }} 年龄:{{ item.age }}</label>
    <button @click="drop(item.id)">删除</button>
  </li>
  <br/>
  <h3>增加</h3>
  <div>
    <form action="">
      学号：<input type="text" placeholder="回车或提交确定" v-model="id"><br>
      姓名：<input type="text" placeholder="回车或提交确定" v-model="name"><br>
      年龄：<input type="text" placeholder="回车或提交确定" v-model="age"><br>
      <button @click.prevent="add" @keydown="add">
        提交
      </button>
    </form>
  </div>
  <h3>修改</h3>
  学号：<input type="text" v-model="id" placeholder="输入要修改的学号">
  <form action="" >
    姓名：<input type="text" placeholder="回车或提交确定" v-model="name"><br>
    年龄：<input type="text" placeholder="回车或提交确定" v-model="age"><br>
  </form>
  <button @click="search(id,name,age)">确定</button>
</template>

<script>
export default {
  name: "MangerSystem",
  data() {
    return {
      display:false,
      id: '',
      name: '',
      age: '',
      people: [
        {id: '1', name: 'py', age: '18'},
        {id: '2', name: 'xb', age: '17'}
      ]
    }
  },
  methods: {
    drop(id) {
      console.log(id)
      console.log(this.people.findIndex(people => people.id === id))
      this.people.splice(this.people.findIndex(people => people.id === id), 1)
    },
    add() {
      const p = {id: this.id, name: this.name, age: this.age}
      let sum = 0
      if (!this.people.length){
        this.people.push(p)
        this.id=''
        this.name=''
        this.age=''
      }else{
        for (let i = 0; i < this.people.length; i++) {
          if (this.people[i].id === p.id) {
            sum++;
          }
        }
        if (sum === 0) {
          this.people.push(p)
          this.id=''
          this.name=''
          this.age=''
        } else {
          alert('已经存在该学号')
        }
      }
    },
    search(id,name,age) {
      let sum = 0
      for (let i = 0; i < this.people.length; i++) {
        if (this.people[i].id === id) {
          this.people[i].name=name
          this.people[i].age=age
        }
      }
    },
  }
}
</script>


<style scoped>

</style>